import Vuex from 'vuex'
import { miniLogin, getTenantId, getCustomerInfo, resetToken } from '@/api/index'
import type { Login_params } from '@/api/index.type'
// import { queryImAccout } from '@/api/im'

const modulesFiles = import.meta.glob('./modules/*.ts', { eager: true })
const modules = Object.keys(modulesFiles).reduce((p, n) => {
  const moduleName = n.replace(/^\.\/modules\/(.+)\.ts$/, '$1')
  const value = modulesFiles[n]
  p[moduleName] = value.default
  return p
}, {})

type State = {
  token: string
  userInfo: object
  appId: string
  windowInfo: object
  system: string
  tenantId: string
  loginCode: string
}

const getters = {}
const state: State = {
  token: uni.getStorageSync('token') || '',
  refreshToken: uni.getStorageSync('refreshToken') || '',
  userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : null,
  appId: 'wx510f8732240f6801',
  windowInfo: {},
  system: '',
  tenantId: uni.getStorageSync('tenantId') || '',
  loginCode: ''
}

const mutations = {
  setToken(state, payload: string) {
    state.token = payload
    if (state.token) {
      uni.setStorageSync('token', payload)
    } else {
      uni.removeStorageSync('token')
    }
  },
  setFreshToken(state, payload: string) {
    state.refreshToken = payload
    if (state.refreshToken) {
      uni.setStorageSync('refreshToken', payload)
    } else {
      uni.removeStorageSync('refreshToken')
    }
  },
  setAppId(state, payload) {
    state.appId = payload
    if (state.appId) {
      uni.setStorageSync('appId', payload)
    } else {
      uni.removeStorageSync('appId')
    }
  },
  setTenantId(state, payload) {
    state.tenantId = payload
    if (state.tenantId) {
      uni.setStorageSync('tenantId', payload)
    } else {
      uni.removeStorageSync('tenantId')
    }
  },
  setLoginCode(state, payload) {
    state.loginCode = payload
  },
  SET_USERINFO(state, payload: object) {
    state.userInfo = payload
    if (String(payload) !== '{}') {
      uni.setStorageSync('userInfo', JSON.stringify(payload))
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  setWindowInfo(state, payload) {
    state.windowInfo = payload
  },
  setSystem(state, payload) {
    state.system = payload
  },
  imStateUpdate(state, payload) {
    state.imState = payload
  }
}

const actions = {
  async getTenantId({ commit, state }) {
    const res = await getTenantId(state.appId)
    if (res.data) {
      commit('setTenantId', res.data.id)
      return Promise.resolve()
    } else {
      return Promise.reject({
        code: 500,
        msg: '未获取租户信息'
      })
    }
  },
  async getToken({ dispatch, commit, state }) {
    const appid = wx.getAccountInfoSync().miniProgram.appId
    console.log(appid)
    commit('setAppId', appid)

    await dispatch('getTenantId')

    await new Promise((resolve, reject) => {
      uni.login({
        success: (res) => {
          commit('setLoginCode', res.code)
          const params: Login_params = {
            type: 34,
            code: res.code,
            state: res.code
          }
          miniLogin(params)
            .then((res) => {
              if (res.code === 0) {
                commit('setToken', res.data.accessToken)
                commit('setFreshToken', res.data.refreshToken)
                resolve()
              } else {
                reject({
                  code: 500,
                  msg: '获取token接口异常'
                })
              }
            })
            .catch((e) => {
              reject(e)
            })
        }
      })
    })
  },
  resetToken({ commit, rootState }) {
    return new Promise((resolve, reject) => {
      const refreshToken = uni.getStorageSync('refreshToken') || ''
      resetToken(refreshToken)
        .then((res) => {
          commit('setToken', res.data.accessToken)
          commit('setFreshToken', res.data.refreshToken)
          resolve()
        })
        .catch((e) => {
          commit('setToken', '')
          commit('setFreshToken', '')
          reject({
            code: 500,
            msg: '令牌刷新失败，请重新登录'
          })
        })
    })
  },
  getUserInfoByToken({ commit }) {
    return new Promise((resolve, reject) => {
      getCustomerInfo()
        .then((res) => {
          if (res.code === 0) {
            commit('SET_USERINFO', res.data)
            resolve(res.data)
          } else {
            reject({
              code: 500,
              msg: '获取用户信息接口异常'
            })
          }
        })
        .catch((e) => {
          reject(e)
        })
    })
  },
  // async imConnect({ dispatch }, payload) {
  //   try {
  //     const { data } = await queryImAccout()
  //     if (data) {
  //       dispatch('im/IM_CONNECT', {
  //         accid: data.accountId,
  //         token: data.token,
  //         appId: '85a4d5b702808cb1cd9809be4e1e5847'
  //       })
  //     } else {
  //       // await Promise.reject({
  //       //   message: '获取im账号失败'
  //       // })
  //       throw new Error('获取im账号失败')
  //     }
  //   } catch (e) {
  //     uni.showToast({
  //       icon: 'none',
  //       title: e.message,
  //       duration: 2000
  //     })
  //   }
  // },
  async setUserInfo({ commit, rootState, dispatch }, payload) {
    try {
      // if (!rootState.token || !rootState.tenantId) {
      await dispatch('getToken')
      // }
      if (!rootState.userInfo) {
        uni.reLaunch({
          url: '/pages/login/index'
        })
        return
      }
      // 未注册
      // const info = await dispatch('getUserInfoByToken')
      // commit('SET_USERINFO', info)
      // if (info.userStatus === 0) {
      //   uni.reLaunch({
      //     url: '/pages/login/index'
      //   })
      // } else {
      //   commit('SET_USERINFO', info)
      //   const { data } = await queryImAccout()
      //   if (data) {
      //     commit('imStateUpdate', 1)
      //     dispatch('im/IM_CONNECT', {
      //       accid: data.accountId,
      //       token: data.token,
      //       appId: '85a4d5b702808cb1cd9809be4e1e5847'
      //     })
      //   } else {
      //     createImAccount()
      //       .then((res) => {
      //         commit('imStateUpdate', 1)
      //         dispatch('im/IM_CONNECT', {
      //           accid: res.data.accountId,
      //           token: res.data.token,
      //           appId: '85a4d5b702808cb1cd9809be4e1e5847'
      //         })
      //       })
      //       .catch((err) => {
      //         commit('imStateUpdate', 0)
      //         uni.showToast({
      //           icon: 'none',
      //           title: err.message,
      //           duration: 2000
      //         })
      //       })
      //   }

      if (payload && payload.success) {
        payload.success()
      } else {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
      // }
    } catch (e) {
      console.log(e)
      if (e.code && e.code === 401) {
        // token师表已有提示不重复提示
      } else if (payload && payload.fail) {
        payload.fail()
      } else {
        uni.showModal({
          title: '提示',
          content: e.msg || '网络异常，点击确定重新登录',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              if (e.code === 1002000005) {
                uni.reLaunch({
                  url: '/pages/login/index'
                })
                return
              }
              dispatch('setUserInfo')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  }
}

const store = new Vuex.Store({
  getters,
  state,
  mutations,
  actions,
  modules
})

export default store
